package parser

import (
	"imooc.com/crawler/engine"
	"regexp"
	"strings"
	"imooc.com/crawler/model"
	"log"
)

const profileInfoReg  = `<div[^>^<]*class="des f-cl"[^>]*>([^<]+)</div>`
var idUrlReg  = regexp.MustCompile(`https://album.zhenai.com/u/([\d]+)`)

func ProfileParser(content []byte,
	url string,
	name string) engine.ParseResult  {
	log.Printf("%v", "User info")

	var profile  model.Profile

	//匹配profileNameReg
	//nameReg := regexp.MustCompile(profileNameReg)
	//nameAll := nameReg.FindAllStringSubmatch(string(content), -1)
	//if nameAll != nil {
	//	for _,m := range nameAll {
	//		profile.Name = m[1]
	//	}
	//}
	profile.Name = name

	//匹配profileNameReg
	infoReg := regexp.MustCompile(profileInfoReg)
	infoAll := infoReg.FindAllStringSubmatch(string(content), -1)
	if infoAll != nil {
		for _,m := range infoAll {
			strs := strings.Split(m[1], "|");
			profile.City = strings.TrimSpace(strs[0])
			profile.Age = strings.TrimSpace(strs[1])
			profile.EB = strings.TrimSpace(strs[2])
			profile.Marriage = strings.TrimSpace(strs[3])
			profile.Height = strings.TrimSpace(strs[4])
			profile.Revenue =strings.TrimSpace(strs[5])
		}
	}
	//把profile的info信息放入到parseResult
	var parseResult engine.ParseResult

	parseResult.Items = []engine.Item {{
		Id : extractString([]byte(url), idUrlReg),
		Type: "zhenai",
		Url: url,
		Payload: profile,
	}}

	return parseResult
}

func extractString(
	content []byte, re *regexp.Regexp) string {
	match := re.FindSubmatch(content)
	if len(match) >= 2  {
		return string(match[1])
	}

	return ""
}


//func ProfileParser(
//	name string) engine.ParserFunc {
//	return func(bytes []byte, url string) engine.ParseResult {
//		return ParseProfile(bytes, url, name)
//	}
//}

type ParseProfile struct {
	username string
}

func (p *ParseProfile) Parse(contents []byte, url string) engine.ParseResult {
	return ProfileParser(contents, url, p.username)
}

func (p *ParseProfile) Serialize() (name string, args interface{}) {
	return "ParseProfile", p.username
}

func NewParseProfile(name string)*ParseProfile  {
	return &ParseProfile{
		username:name,
	}
}
